package com.iceclean.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author : Ice'Clean
 * @date : 2021-05-13
 *
 *
 */
public class MyConnectionPoolImpl implements MyConnectionPool {

    private static final String RESOURCE_NAME = "postBar";
    private static final String URL;
    private static final String USER;
    private static final String PASSWORD;

    /**
     * 数据库连接的存放池
     */
    private final List<Connection> connPool = new LinkedList<>();

    /**
     * 最大的空闲连接数量（默认10）
     */
    private int maxFreeConnections = 10;

    // 在静态代码块中注册驱动
    static
    {
        ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_NAME);
        URL = bundle.getString("url");
        USER = bundle.getString("user");
        PASSWORD = bundle.getString("password");

        try {
            Class.forName(bundle.getString("driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        // 如果连接池为空，新建连接
        if (connPool.isEmpty()) {
            connPool.add(DriverManager.getConnection(URL, USER, PASSWORD));
        }
        // 给出一个数据库连接
        return connPool.remove(0);
    }


    @Override
    public void initPool() throws SQLException {
        // 获取数据库连接并放入数据库连接池中
        for (int i = 0; i < maxFreeConnections; i++) {
            connPool.add(DriverManager.getConnection(URL, USER, PASSWORD));
        }
    }

    @Override
    public void closeConnection(Connection conn) throws SQLException {
        // 如果连接池中的连接数量小于最大数量，且该连接可用
        if (!conn.isClosed()) {
            if (connPool.size() < maxFreeConnections) {
                //则将空闲连接放进去
                connPool.add(conn);
            } else {
                // 否则将连接关闭
                conn.close();
            }
        }
    }

    @Override
    public void setMaxFreeConnections(int maxFreeConnections) {
        this.maxFreeConnections = maxFreeConnections;
    }

    @Override
    public int getMaxFreeConnections() {
        return maxFreeConnections;
    }
}
